package com.ruoyi.quartz.task;

import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.*;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.redis.RedisUtil;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时任务调度测试
 *
 * @author admin
 */
@Component("smjmsXLMOrderCheckTask")
public class SmjmsXLMOrderCheckTask {
    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;
    @Resource
    private LoginService loginService;
    private Log logger = Log.get();

    @Autowired
    private ITSmjGoodListService itSmjGoodListService;

    @Autowired
    private ITSmjMachineListService itSmjMachineListService;

    @Autowired
    private ITSmjOrderInfoService itSmjOrderInfoService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    public void checkOrder() throws Exception {
//        logger.info("CXZF订单查询..");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        TOrderInfo query = new TOrderInfo();
//        query.setChannelType("alipay");
        query.setChannel("smj_xlm");
        query.setStatus(1);
        String newdateTime = DateUtils.dealDate("10分钟前");
//        String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        query.getParams().put("beginCreateTime", newdateTime);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoListByNoAuth(query);
        for (TOrderInfo orderInfo : orderInfos) {
            synchronized (this) {
                if (orderInfo.getValidTime().before(new Date()) || StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                    continue;
                }
//

                if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                    continue;
                }
                TSmjGoodList tSmjGoodList = itSmjGoodListService.selectTSmjGoodListById(Long.valueOf(orderInfo.getQrcodeTxt()));
                if (tSmjGoodList == null) {
                    continue;
                }
                TSmjMachineList tSmjMachineList = itSmjMachineListService.selectTSmjMachineListById(tSmjGoodList.getMachineId());
                TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
                String accountJson = userRecipientInfo.getAccountJson();
                JSONObject accountObj = JSONObject.parseObject(accountJson);
                HashMap<String, String> headerMap = new HashMap();
//                headerMap.put("Cookie", accountObj.getString("cookie"));
                headerMap.put("User-Agent", "Mozilla/5.0 (Linux; Android 9; PJU110 Build/PQ3A.190801.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/105.0.5195.148 MYWeb/0.11.0.240912194432 UWS/3.22.2.9999 UCBS/3.22.2.9999_220000000000 Mobile Safari/537.36 NebulaSDK/1.8.100112 Nebula AlipayDefined(nt:WIFI,ws:360|0|2.0) AliApp(AP/10.6.50.8000) AlipayClient/10.6.50.8000 Language/zh-Hans useStatusBar/true isConcaveScreen/false Region/CNAriver/1.0.0");
                HashMap<String, String> requestMap = new HashMap();
                //String orderUrl = "https://xxh.aotaki.com/api/gprsSale/h5Search";
                String orderUrl = "https://vmpay.aotaki.com/trade/checkTradeResult";
                requestMap.put("vmCode", tSmjMachineList.getMachineName());
                requestMap.put("key", orderInfo.getGoodsName());
                HttpResponse httpResponse = HttpUtils.httpFormPost(orderUrl, headerMap, "", requestMap, "", "");
                JSONObject result = JSONObject.parseObject(httpResponse.getBody());
                logger.info("查单返回：{}", result);
                if("finish".equals(result.getString("state"))) {
                    tSmjGoodList.setGoodNum(tSmjGoodList.getGoodNum() - 1);
                    logger.info("商品剩余数量：{}", tSmjGoodList.getGoodNum());
                    itSmjGoodListService.updateTSmjGoodList(tSmjGoodList);
                    MsgPayResult msgPayResult = new MsgPayResult();
                    msgPayResult.setChannel(orderInfo.getChannel());
                    msgPayResult.setTradeNo(orderInfo.getId().toString());
                    msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                    msgPayResult.setOrderId(orderInfo.getPay3rdOrderNo());
                    msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                    msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                    msgPayResult.setBillTime("");

                    msgPayResult.setChannelPayMsgResult(result.toJSONString());
                    ResponseData responseData = chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                    chargeService.notifyUserPaySucc(orderInfo.getId());

                    logger.info("售货机订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney() + " 处理结果：{}", responseData.getSuccess());
                }





                    /**
                String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
//                HashMap<String, String> headerMap = new HashMap();
//                headerMap.put("Cookie", accountObj.getString("cookie"));
//                headerMap.put("User-Agent", accountObj.getString("User-Agent"));
                LocalDate now = LocalDate.now();



                requestMap.put("saleTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

                requestMap.put("deptId", accountObj.getString("deptId"));
                requestMap.put("saleOrderNo", "");
                requestMap.put("saleLocId", tSmjMachineList.getSmMachineId());
                requestMap.put("saleOrderNo", "");
                requestMap.put("tradeState", "");
                requestMap.put("refundState", "0");
                requestMap.put("allFlg", "1");
                requestMap.put("pageIndex", "0");
                requestMap.put("pageSize", "15");
                logger.info("查单参数：{}", JSON.toJSONString(requestMap));
                HttpResponse httpResponse = HttpUtils.httpFormPost(orderUrl, headerMap, accountObj.getString("cookie"), requestMap, "", "");
                logger.info("重新查询网关地址：{}：结果：{}", orderUrl, httpResponse == null ? "未查询到信息" : "已查询到信息");

                if (httpResponse == null) {
                    logger.info("未登录重新登录查询订单");
                    userRecipientInfo = reLogin(userRecipientInfo);
                    accountObj = JSONObject.parseObject(userRecipientInfo.getAccountJson());
                    headerMap.put("Cookie", accountObj.getString("cookie"));
                    httpResponse = rePaydetail(userRecipientInfo, requestMap, orderUrl);
                }
                JSONObject rsInfo = JSONObject.parseObject(httpResponse.getBody());
                logger.info(rsInfo.toJSONString());
                JSONArray resultList = rsInfo.getJSONObject("page").getJSONArray("rows");
                for (int i = 0; i < resultList.size(); i++) {
                    JSONObject result = (JSONObject) resultList.get(i);
                    Date payTime = sdf.parse(result.getString("saleTime"));
                    logger.info("机器名称：{},货道:{},金额：{}，支付时间：{}", result.getString("saleLocName"), result.getString("rackNo"), result.getString("salePrice"), result.getString("saleTime"));
                    TSmjOrderInfo tSmjOrderInfo = new TSmjOrderInfo();
                    tSmjOrderInfo.setRealChanleOrderNo(result.getString("tradeNo")+System.lineSeparator()+result.getString("outTradeNo"));
                    tSmjOrderInfo.setMachineName(result.getString("saleLocName"));
                    tSmjOrderInfo.setHdCode(result.getString("rackNo"));
                    tSmjOrderInfo.setPayAmount(result.getString("salePrice"));
                    tSmjOrderInfo.setPayTime(payTime);
                    tSmjOrderInfo.setPayType(result.getString("payment"));
                    tSmjOrderInfo.setUserId(userRecipientInfo.getUserId());
                    List<TSmjOrderInfo> tSmjOrderInfoList = itSmjOrderInfoService.selectTSmjOrderInfoListByNoAuth(tSmjOrderInfo);

                    if (tSmjOrderInfoList.size() == 0) {
                        tSmjOrderInfo.setStatus(0);
                        itSmjOrderInfoService.insertTSmjOrderInfo(tSmjOrderInfo);
                    } else {
                        tSmjOrderInfo = tSmjOrderInfoList.get(0);
                    }
                    boolean flag = false;
                    logger.info("支付时间是否大于更新时间：{},支付时间是否小于失效时间:{}", payTime.after(orderInfo.getUpdateTime()), payTime.before(orderInfo.getValidTime()));

                    if (payTime.after(orderInfo.getUpdateTime()) && payTime.before(orderInfo.getValidTime())) {
                        logger.info("订单修改时间：{},订单支付时间:{},订单失效时间：{}", sdf.format(orderInfo.getUpdateTime()), sdf.format(payTime), sdf.format(orderInfo.getValidTime()));
                        flag = true;
                    }
                    BigDecimal payAmount = new BigDecimal(orderInfo.getMoney() / 100).setScale(2);
                    //if (result.getString("outTradeNo").equals(orderInfo.getPay3rdOrderNo()) && result.getString("saleLocName").equals(orderInfo.getQrcodeContent()) && result.getString("rackNo").equals(tSmjGoodList.getGoodHd()) && new BigDecimal(result.getString("salePrice")).compareTo(payAmount) == 0 && flag) {
                    if (result.getString("outTradeNo").equals(orderInfo.getPay3rdOrderNo()) && result.getString("saleLocName").equals(orderInfo.getQrcodeContent()) && result.getString("rackNo").equals(tSmjGoodList.getGoodHd()) && new BigDecimal(result.getString("salePrice")).compareTo(payAmount) == 0) {
                        tSmjGoodList.setGoodNum(tSmjGoodList.getGoodNum() - 1);
                        logger.info("商品剩余数量：{}", tSmjGoodList.getGoodNum());
                        itSmjGoodListService.updateTSmjGoodList(tSmjGoodList);
                        tSmjOrderInfo = itSmjOrderInfoService.selectTSmjOrderInfoById(tSmjOrderInfo.getId());
                        tSmjOrderInfo.setStatus(1);
                        tSmjOrderInfo.setOrderCode(orderInfo.getId().toString());
                        tSmjOrderInfo.setMerOrderNo(orderInfo.getOutTradeNo());
                        tSmjOrderInfo.setCustomOrderNo(orderInfo.getCustomOrderNo());
                        itSmjOrderInfoService.updateTSmjOrderInfo(tSmjOrderInfo);

                        MsgPayResult msgPayResult = new MsgPayResult();
                        msgPayResult.setChannel(orderInfo.getChannel());
                        msgPayResult.setTradeNo(orderInfo.getId().toString());
                        msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                        msgPayResult.setOrderId(orderInfo.getPay3rdOrderNo());
                        msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                        msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                        msgPayResult.setBillTime(sdf.format(payTime));

                        msgPayResult.setChannelPayMsgResult(result.toJSONString());
                        ResponseData responseData = chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                        logger.info("售货机订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney() + " 处理结果：{}", responseData.getSuccess());
                    }

                }
                     **/
            }
        }
    }


    private TRecipientInfo reLogin(TRecipientInfo tRecipientInfo) {
        String accountJson = tRecipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
        logger.info("后台登录HTMLurl：" + accountObj.getString("loginUrl"));
        HttpResponse httpResponse = HttpUtils.httpFormGet(accountObj.getString("loginUrl"), headerMap, "", "售货机【小懒猫】", "");
        String cookies = httpResponse.getCookie();
        headerMap.put("Cookie", cookies);
        logger.info("登录cookies：{}", cookies);
        accountObj.put("cookie", cookies);
        accountObj.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
        HashMap<String, String> requestMap = new HashMap();
        requestMap.put("userCode", tRecipientInfo.getChannelAccount());
        requestMap.put("password", accountObj.getString("password"));
        logger.info("登录地址：{},用户名：{},password:{}", "https://xxh.aotaki.com/api/h5b/login", tRecipientInfo.getChannelAccount(), accountObj.getString("password"));
        HttpResponse b = HttpUtils.httpFormPost("https://xxh.aotaki.com/api/h5b/login", headerMap, cookies, requestMap, "售货机【小懒猫】", "");
        logger.info("登录结果", b.getBody());
        cookies = b.getCookie();
        accountObj.put("cookie", cookies);
        String userStr = b.getBody();
        JSONObject userObj = JSONObject.parseObject(userStr);
        if (!userObj.getBooleanValue("success")) {
            return tRecipientInfo;
        }
        tRecipientInfo.setAccountJson(accountObj.toJSONString());
        userRecipientService.updateTRecipientInfo(tRecipientInfo);
        return tRecipientInfo;
    }

    private HttpResponse rePaydetail(TRecipientInfo tUserRecipientInfo, HashMap<String, String> dataMap, String operUrl) {
        JSONObject accountObj = JSONObject.parseObject(tUserRecipientInfo.getAccountJson());
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
        headerMap.put("Cookie", accountObj.getString("cookie"));
        HttpResponse httpResponse = HttpUtils.httpFormPost(operUrl, headerMap, accountObj.getString("cookie"), dataMap, "", "");
        logger.info("重新查询网关地址：{}：结果：{}", operUrl, httpResponse == null ? "未查询到信息" : "已查询到信息");
        if (httpResponse == null)
            return rePaydetail(tUserRecipientInfo, dataMap, operUrl);
        return httpResponse;
    }

    private String timeStamp2Date(String str_num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }

    public void delSmjSmOrder() {
        TSmjOrderInfo query = new TSmjOrderInfo();
        String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        query.getParams().put("beginCreateTime", dateTime + " 00:00:00");
        itSmjOrderInfoService.deleteTSmjOrderInfo(query);
    }

    public void anyscGoods() {
        TSmjMachineList query = new TSmjMachineList();
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        query.setMachineType("XIAOLANMAO");
        List<TSmjMachineList> tSmjMachineLists = itSmjMachineListService.selectTSmjMachineListListByNoAuth(query);
        for (TSmjMachineList tSmjMachineList : tSmjMachineLists) {
            TRecipientInfo tUserRecipientInfo = userRecipientService.selectTRecipientInfoById(tSmjMachineList.getUserRecipientId());
//        TRealChannelConfig tRealChannelConfig = tRealChannelConfigMapper.selectTRealChannelConfigByRealChannelCode(tSmjMachineList.getRealChannelCode());
//        JSONObject rsCfgObj = JSONObject.parseObject(tRealChannelConfig.getReturnParamCfg());
//        JSONObject reqObj = JSONObject.parseObject(tRealChannelConfig.getRequestParam());
            String accountJson = tUserRecipientInfo.getAccountJson();
            JSONObject accountObj = JSONObject.parseObject(accountJson);
            headerMap.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
            headerMap.put("Cookie", accountObj.getString("cookie"));
            dataMap.put("saleLocId", tSmjMachineList.getSmMachineId());
            HttpResponse httpResponse = HttpUtils.httpFormPost("https://xxh.aotaki.com/api/rackDeploy/h5b/initSaleLocStatus18", headerMap, accountObj.getString("cookie"), dataMap, "售货机【小懒猫】", "");
            if (httpResponse == null) {
                tUserRecipientInfo = reLogin(tUserRecipientInfo);
                accountObj = JSONObject.parseObject(tUserRecipientInfo.getAccountJson());
//                httpResponse =  HttpUtils.httpFormPost("https://xxh.aotaki.com/api/rackDeploy/h5b/initSaleLocStatus18",headerMap,accountObj.getString("cookie"),dataMap,"售货机【小懒猫】","");
                httpResponse = rePaydetail(tUserRecipientInfo, dataMap, "https://xxh.aotaki.com/api/rackDeploy/h5b/initSaleLocStatus18");
            }
            JSONObject jsonObject = JSONObject.parseObject(httpResponse.getBody());
            JSONArray rackDetails = jsonObject.getJSONArray("rackDetails");
            for (int i = 0; i < rackDetails.size(); i++) {
                JSONObject rackDetail = rackDetails.getJSONObject(i);
                TSmjGoodList tSmjGoodList = new TSmjGoodList();
                tSmjGoodList.setMachineId(tSmjMachineList.getId());
//            tSmjGoodList.setRealChannelCode(tSmjMachineList.getRealChannelCode());
                tSmjGoodList.setMachineType(tSmjMachineList.getMachineType());
                String hd = rackDetail.getString("rackNo");
                tSmjGoodList.setGoodHd(hd);
                tSmjGoodList.setPayType("ALI");
                tSmjGoodList.setRealChannelCode("alipay_smj_xlm_h5");
                List<TSmjGoodList> tSmjGoodLists = itSmjGoodListService.selectTSmjGoodListListByNoAuth(tSmjGoodList);
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList = tSmjGoodLists.get(0);
                }
                tSmjGoodList.setUserId(tUserRecipientInfo.getUserId());

                //获取商品链接
                tSmjGoodList.setGoodUrl(rackDetail.getString("visionImageUrl"));

                tSmjGoodList.setGoodName(rackDetail.getString("goodsName"));
                tSmjGoodList.setSmGoodId(rackDetail.getString("goodId"));
                tSmjGoodList.setGoodNum(rackDetail.getLongValue("goodNum"));
                tSmjGoodList.setGoodPrice(rackDetail.getBigDecimal("noncashPrice").setScale(2));
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList.setUpdateTime(new Date());
                    itSmjGoodListService.updateTSmjGoodList(tSmjGoodList);
                } else {
                    tSmjGoodList.setGoodStatus(0);
                    itSmjGoodListService.insertTSmjGoodList(tSmjGoodList);
                }
                tSmjGoodList = new TSmjGoodList();
                tSmjGoodList.setMachineType(tSmjMachineList.getMachineType());
                tSmjGoodList.setMachineId(tSmjMachineList.getId());
                tSmjGoodList.setGoodHd(hd);
                tSmjGoodList.setPayType("WX");
                tSmjGoodList.setRealChannelCode("wechat_smj_xlm_h5");
                tSmjGoodLists = itSmjGoodListService.selectTSmjGoodListListByNoAuth(tSmjGoodList);
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList = tSmjGoodLists.get(0);
                }
                tSmjGoodList.setUserId(tUserRecipientInfo.getUserId());
                tSmjGoodList.setGoodUrl(rackDetail.getString("visionImageUrl"));

                tSmjGoodList.setGoodName(rackDetail.getString("goodsName"));
                tSmjGoodList.setSmGoodId(rackDetail.getString("goodId"));
                tSmjGoodList.setGoodNum(rackDetail.getLongValue("goodNum"));
                tSmjGoodList.setGoodPrice(rackDetail.getBigDecimal("noncashPrice").setScale(2));
                if (tSmjGoodLists.size() > 0) {
                    tSmjGoodList.setUpdateTime(new Date());
                    itSmjGoodListService.updateTSmjGoodList(tSmjGoodList);
                } else {
                    tSmjGoodList.setGoodStatus(0);
                    itSmjGoodListService.insertTSmjGoodList(tSmjGoodList);
                }
                //刪除redis緩存
                logger.info("小懒猫删除缓存KEY:{}","PLATFORM_SMJXLMALI"+tUserRecipientInfo.getId()+tSmjGoodList.getGoodPrice());
//                redisUtil.remove("PLATFORM_SMJXLMALI"+tUserRecipientInfo.getId()+tSmjGoodList.getGoodPrice());
//                redisUtil.remove("PLATFORM_SMJXLMWX"+tUserRecipientInfo.getId()+tSmjGoodList.getGoodPrice());
            }
            redisUtil.removePattern("PLATFORM_SMJXLMALI*");
            redisUtil.removePattern("PLATFORM_SMJXLMWX*");
            tSmjMachineList.setUpdateTime(DateUtils.getNowDate());
            itSmjMachineListService.updateTSmjMachineList(tSmjMachineList);
        }
    }

    private String decodeQR(String filePath) {
//        String filePath = "E:/txdata/data/images/qrCode.jpg";//二维码路径
        BufferedImage image;
        Result result = null;
        try {
            image = ImageIO.read(new File(filePath));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
            logger.info("图片中内容：  ");
            logger.info("author： " + result.getText());
            logger.info("图片中格式：  ");
            logger.info("encode： " + result.getBarcodeFormat());
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }




    public void anyscGoodsNum() throws Exception {
        TSmjMachineList query = new TSmjMachineList();
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        query.setMachineType("XIAOLANMAO");
        List<TSmjMachineList> tSmjMachineLists = itSmjMachineListService.selectTSmjMachineListListByNoAuth(query);
        for (TSmjMachineList tSmjMachineList : tSmjMachineLists) {
            TSmjGoodList queryTSmjGoodList = new TSmjGoodList();
            queryTSmjGoodList.setMachineId(tSmjMachineList.getId());
            List<TSmjGoodList> tSmjGoodLists = itSmjGoodListService.selectTSmjGoodListListByNoAuth(queryTSmjGoodList);
            boolean isUpdate = false;
            for (TSmjGoodList tSmjGoodList : tSmjGoodLists) {
                if(tSmjGoodList.getGoodNum()<=2){
                    TRecipientInfo tUserRecipientInfo = userRecipientService.selectTRecipientInfoById(tSmjMachineList.getUserRecipientId());
                    String accountJson = tUserRecipientInfo.getAccountJson();
                    JSONObject accountObj = JSONObject.parseObject(accountJson);
                    headerMap.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
                    headerMap.put("Cookie", accountObj.getString("cookie"));
                    dataMap.put("saleLocId", tSmjMachineList.getSmMachineId());
                    HttpResponse httpResponse = HttpUtils.httpFormPost("https://xxh.aotaki.com/api/remoteAccount/h5b/initRemoteReplenishment", headerMap, accountObj.getString("cookie"), dataMap, "售货机【小懒猫】", "");
                    if (httpResponse == null) {
                        tUserRecipientInfo = reLogin(tUserRecipientInfo);
                        httpResponse = rePaydetail(tUserRecipientInfo, dataMap, "https://xxh.aotaki.com/api/remoteAccount/h5b/initRemoteReplenishment");
                    }
                    JSONObject jsonObject = JSONObject.parseObject(httpResponse.getBody());
//            logger.info("initRemoteReplenishment:{}",JSONObject.toJSONString(jsonObject));
                    JSONArray rackDetails = jsonObject.getJSONArray("saleLocRackDetails");
                    for (int i = 0; i < rackDetails.size(); i++) {
                        JSONObject rackDetail = rackDetails.getJSONObject(i);
                        if (rackDetail.getIntValue("goodNum") <= 2) {
                            /**
                             * "changeValue": -5,
                             *     "defaultFullReplenishment": 5,
                             *     "color": "red"
                             */
                            rackDetail.put("changeValue", 10 - rackDetail.getIntValue("goodNum"));
                        } else {
                            rackDetail.put("changeValue", 0);
                        }
                        rackDetail.put("defaultFullReplenishment", 10);
                        if (i == 0) {
                            rackDetail.put("color", "red");
                        } else {
                            rackDetail.put("color", "black");
                        }
                    }
                    headerMap.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
                    headerMap.put("Cookie", accountObj.getString("cookie"));
                    dataMap.put("saleLocId", tSmjMachineList.getSmMachineId());
                    dataMap.put("saleLocRackDetails", JSONObject.toJSONString(rackDetails));
//            logger.info("remoteReplenishment:{}",JSONObject.toJSONString(dataMap));
                    httpResponse = HttpUtils.httpFormPost("https://xxh.aotaki.com/api/remoteAccount/h5b/remoteReplenishment", headerMap, accountObj.getString("cookie"), dataMap, "售货机【小懒猫】", "");
                    if (httpResponse == null) {
                        tUserRecipientInfo = reLogin(tUserRecipientInfo);
                        accountObj = JSONObject.parseObject(tUserRecipientInfo.getAccountJson());
//                httpResponse =  HttpUtils.httpFormPost("https://xxh.aotaki.com/api/rackDeploy/h5b/initSaleLocStatus18",headerMap,accountObj.getString("cookie"),dataMap,"售货机【小懒猫】","");
                        httpResponse = rePaydetail(tUserRecipientInfo, dataMap, "https://xxh.aotaki.com/api/remoteAccount/h5b/remoteReplenishment");
                    }
                    logger.info("同步商品：{}", httpResponse.getBody());
                    isUpdate = true;
                    break;
                }
            }
            if(isUpdate){
                queryTSmjGoodList.setGoodNum(10l);
                itSmjGoodListService.updateTSmjGoodNum(queryTSmjGoodList);
            }

        }
    }


    private void insertSmjOrderByDelivery(Elements trs, TSmjMachineList tSmjMachineList, TRecipientInfo userRecipientInfo) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < trs.size() - 1; i++) {
            Element tr = trs.get(i);
            Elements cells = tr.select("td");
            String hd = cells.get(1).text();
            String price = cells.get(3).text();
            BigDecimal payAmount = new BigDecimal(price).setScale(2);
            Date payTime = sdf.parse(cells.get(4).text());
            TSmjOrderInfo tSmjOrderInfo = new TSmjOrderInfo();
            tSmjOrderInfo.setHdCode(hd);
            tSmjOrderInfo.setPayAmount(payAmount.toString());
            tSmjOrderInfo.setPayTime(payTime);
            tSmjOrderInfo.setUserId(userRecipientInfo.getUserId());
            tSmjOrderInfo.setRealChanleOrderNo(cells.get(6).text());
            tSmjOrderInfo.setPayType("支付宝");
            List<TSmjOrderInfo> tSmjOrderInfoList = itSmjOrderInfoService.selectTSmjOrderInfoListByNoAuth(tSmjOrderInfo);
            if (tSmjOrderInfoList.size() == 0) {
                tSmjOrderInfo.setMachineName(tSmjMachineList.getMachineName());
                tSmjOrderInfo.setStatus(0);
                itSmjOrderInfoService.insertTSmjOrderInfo(tSmjOrderInfo);
            }
        }
    }


    private HttpResponse getDeliveryPost(TRecipientInfo userRecipientInfo, TSmjMachineList tSmjMachineList) {
        String accountJson = userRecipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("Cookie", accountObj.getString("cookie"));
        headerMap.put("User-Agent", accountObj.getString("User-Agent"));
        HttpResponse deliveryGet = HttpUtils.httpFormGet(loginUrls[0] + "operator/delivery.html?id=" + tSmjMachineList.getSmMachineId(), headerMap, "", "");
        String cookies = deliveryGet.getCookie();
        HashMap<String, String> requestMap = new HashMap();
        LocalDate now = LocalDate.now();
        requestMap.put("startTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00:00");
        LocalDate tomorrow = now.plusDays(1);
        requestMap.put("endTime", tomorrow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00:00");
        requestMap.put("id", tSmjMachineList.getSmMachineId());
        requestMap.put("pageno", "");
        HttpResponse deliveryPost = HttpUtils.httpFormPost(loginUrls[0] + "operator/delivery.html", headerMap, cookies, requestMap, "售货机【盛马】", "");
        if (deliveryPost.getBody().contains("登录")) {
            userRecipientInfo = reLogin(userRecipientInfo);
            return getDeliveryPost(userRecipientInfo, tSmjMachineList);
        }
        return deliveryPost;
    }


    private void insertSmjOrderByRefund(Elements trs, TSmjMachineList tSmjMachineList, TRecipientInfo userRecipientInfo) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < trs.size() - 1; i++) {
            Element tr = trs.get(i);
            Elements cells = tr.select("td");
            String hd = cells.get(4).text();
            String price = cells.get(7).text();
            BigDecimal payAmount = new BigDecimal(price).setScale(2);
            Date payTime = sdf.parse(cells.get(10).text());
            TSmjOrderInfo tSmjOrderInfo = new TSmjOrderInfo();
            tSmjOrderInfo.setRealChanleOrderNo(cells.get(1).text());
            tSmjOrderInfo.setMachineName(cells.get(3).text());
            tSmjOrderInfo.setHdCode(hd);
            tSmjOrderInfo.setPayAmount(payAmount.toString());
            tSmjOrderInfo.setPayTime(payTime);
            tSmjOrderInfo.setPayType(cells.get(6).text());
            tSmjOrderInfo.setUserId(userRecipientInfo.getUserId());
            List<TSmjOrderInfo> tSmjOrderInfoList = itSmjOrderInfoService.selectTSmjOrderInfoListByNoAuth(tSmjOrderInfo);
            if (tSmjOrderInfoList.size() == 0) {
                tSmjOrderInfo.setStatus(0);
                itSmjOrderInfoService.insertTSmjOrderInfo(tSmjOrderInfo);
            }
        }
    }


    private HttpResponse getRefundGet(TRecipientInfo userRecipientInfo, TSmjMachineList tSmjMachineList) {
        String accountJson = userRecipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("Cookie", accountObj.getString("cookie"));
        headerMap.put("User-Agent", accountObj.getString("User-Agent"));
        HttpResponse deliveryGet = HttpUtils.httpFormGet(loginUrls[0] + "operator/refund.html", headerMap, "", "");
        if (deliveryGet.getBody().contains("登录")) {
            userRecipientInfo = reLogin(userRecipientInfo);
            return getRefundGet(userRecipientInfo, tSmjMachineList);
        }
        return deliveryGet;
    }

}
